/*ic_arrow_list_blac
 * @Description: File Description
 * @Author: jundie.cheng@hand-china.com
 * @version: H3.0
 * @Date: 2023-03-28 15:33:13
 * @LastEditTime: 2023-03-28 15:35:29
 */
import type { BIWDController } from './definition'
import type { Worker } from '@/controller/base/types/worker'
import type { Remote } from '@/controller/base/types/remote'
import { useWorker, useRemote, wrapSafeActions } from '@/controller/base/index'
import { RemoteTypes } from '@/controller/base/remote'
import { createBaseState, BaseGetters, BaseActions, createBaseApplianceControl } from '../BaseAppliance'
import { defineStore } from 'pinia'
import {
  ChildLock,
  Filter1Usage,
  Filter2Usage,
  Filter1Rest,
  Filter2Rest,
  TDSRawWater,
  TDSPureWater,
  MachineUseTime,
  MachineFilterVolume,
  LocalControlActive,
  OperationState,
  NightModeStartTime,
  NightModeEndTime,
  NightModeBright,
  NightModeState,
  StandbyTime,
  MachineError,
  DescalingStatus,
  DoorState,
  BIWD_WATERTREATMENT_CUSTOM_TEMPERATURE,
  BIWD_WATERTREATMENT_CUSTOM_FILLQUANTITY,
  BIWD_WATERTREATMENT_CHILLEDWATERSET,
  BIWD_WATERTREATMENT_CHILLEDWATERTEMPERATURE,
  BIWD_WATERTREATMENT_Filter1Usage,
  BIWD_WATERTREATMENT_Filter2Usage,
  BIWD_WATERTREATMENT_Filter1Rest,
  BIWD_WATERTREATMENT_Filter2Rest,
  BIWD_WATERTREATMENT_BEFOREFILTERTDS,
  BIWD_WATERTREATMENT_AFTERFILTERTDS,
  BIWD_WATERTREATMENT_MachineUseTime,
  BIWD_WATERTREATMENT_AFTERFILTERQUANTITY,
  BIWD_WATERTREATMENT_DescalingStatus,
  BIWD_WATERTREATMENT_ERRORCODE,
  BIWD_WATERTREATMENT_BEFOREFILTERQUANTITY,
  ChildLockSet,
  BIWD_WATERTREATMENT_CHILDLOCKHIGHTEMPERATURE,
  UPGRADE_MCUSTATUS,
  ProductVolume,
} from '@/constants/WDCommand'
import type { Binder } from '../base/types/binder'
import type { ApplianceSetting } from '@/api/appliance'
import { actionDebounce } from '@/utils/mpHelper'

/**
 * 初始化数据
 */
export const createBIWDState: () => BIWDController.State = () => ({
  ...createBaseState(),
  oemDoorState: 0,
  childLock: 0,
  childLockSet: -1,
  childLockInHotWater: -1,
  filter1Usage: 0,
  filter2Usage: 0,
  filter1Rest: 0,
  filter2Rest: 0,
  TdsRawWater: 0,
  TdsPureWater: 0,
  machineUseTime: 0,
  machineFilterVolume: 0,
  isLocalOperate: false, //本地操作状态
  runState: -1, //本地操作状态
  operateState: '',
  cleanState: -1, //清洁状态
  nightModeState: 0,
  nightModeStartHour: '00',
  nightModeStartMinute: '00',
  nightModeEndHour: '00',
  nightModeEndMinute: '00',
  nightModeBright: 0,
  sleepTime: 2,
  errorCode: 0,
  valueErrorCode: 0,
  customTemp: '',
  customMill: '',
  isCoolWater: false,
  coolWaterSwitch: 0,
  coolWaterTemp: 0,
  mcuStatus: 0,
  productVolume: 0,
})
export const BIWDGetters: BIWDController.Getters = {
  ...BaseGetters,
  isFavorite({ _datasource: { settings } }) {
    return settings.some((setting) => setting.key.indexOf('Setting.FavoriteProgram') !== -1)
  },
  isCustom({ _datasource: { settings } }) {
    return settings.some(
      (setting) =>
        setting.key === BIWD_WATERTREATMENT_CUSTOM_TEMPERATURE ||
        setting.key === BIWD_WATERTREATMENT_CUSTOM_FILLQUANTITY
    )
  },
  runSelectedDisabled() {
    return true
  },
}
export const BIWDActions: BIWDController.Actions = wrapSafeActions<BIWDController.Store, BIWDController.Actions>({
  ...BaseActions,
})

/**
 * 组合API
 */
const useStore = defineStore<'BIWD', BIWDController.State, BIWDController.Getters, BIWDController.Actions>('BIWD', {
  state: createBIWDState,
  getters: BIWDGetters,
  actions: BIWDActions,
})

// 组件使用
export function useBIWDControl(): BIWDController.Control {
  const store = useStore() as BIWDController.Store
  const worker = useWorker(store) as Worker.ApplianceWorker<BIWDController.Store>
  const remote = useRemote(store) as Remote.ApplianceRemote<BIWDController.Store>
  return { store, worker, remote }
}

// 页面使用
export function createBIWDControl(control: BIWDController.Control = useBIWDControl()): BIWDController.Control {
  const { store, worker, remote } = control

  const loadData = actionDebounce({
    call: async () => {
      const tasks = []
      if (store.isOffline === false) {
        tasks.push(remote.loadAllSetting())
      }
      return Promise.all(tasks)
    },
  })

  createBaseApplianceControl(control, {
    remoteType: RemoteTypes.Oem,
    remoteControlPatcher: (patchState, reference) => {
      patchState.remoteControl = Number(reference.value) === 1
    },
    remoteStartPatcher: (patchState, reference) => {
      patchState.remoteStart = Number(reference.value) === 1
    },
  })

  useBIWDBinding(control)
  worker.onLoad(loadData)
  worker.onShow(loadData)

  return control
}

export function useBIWDBinding(control: BIWDController.Control) {
  const { worker } = control

  // Settings监听
  const syncMap: Partial<Record<keyof BIWDController.State, string | string[]>> = {
    oemDoorState: DoorState,
    childLock: ChildLock,
    childLockSet: ChildLockSet,
    childLockInHotWater: BIWD_WATERTREATMENT_CHILDLOCKHIGHTEMPERATURE,
    filter1Usage: [Filter1Usage, BIWD_WATERTREATMENT_Filter1Usage],
    filter2Usage: [Filter2Usage, BIWD_WATERTREATMENT_Filter2Usage],
    filter1Rest: [Filter1Rest, BIWD_WATERTREATMENT_Filter1Rest],
    filter2Rest: [Filter2Rest, BIWD_WATERTREATMENT_Filter2Rest],
    TdsRawWater: [TDSRawWater, BIWD_WATERTREATMENT_BEFOREFILTERTDS],
    TdsPureWater: [TDSPureWater, BIWD_WATERTREATMENT_AFTERFILTERTDS],
    machineUseTime: [MachineUseTime, BIWD_WATERTREATMENT_MachineUseTime],
    machineFilterVolume: [MachineFilterVolume, BIWD_WATERTREATMENT_BEFOREFILTERQUANTITY],
    isLocalOperate: LocalControlActive,
    cleanState: [DescalingStatus, BIWD_WATERTREATMENT_DescalingStatus],
    nightModeStartHour: NightModeStartTime,
    nightModeStartMinute: NightModeStartTime,
    nightModeEndHour: NightModeEndTime,
    nightModeEndMinute: NightModeEndTime,
    nightModeBright: NightModeBright,
    nightModeState: NightModeState,
    sleepTime: StandbyTime,
    errorCode: MachineError,
    valueErrorCode: BIWD_WATERTREATMENT_ERRORCODE,
    customTemp: BIWD_WATERTREATMENT_CUSTOM_TEMPERATURE,
    customMill: BIWD_WATERTREATMENT_CUSTOM_FILLQUANTITY,
    coolWaterSwitch: BIWD_WATERTREATMENT_CHILLEDWATERSET,
    coolWaterTemp: BIWD_WATERTREATMENT_CHILLEDWATERTEMPERATURE,
    mcuStatus: UPGRADE_MCUSTATUS,
    productVolume: [ProductVolume, BIWD_WATERTREATMENT_AFTERFILTERQUANTITY],
  }
  Object.entries(syncMap).forEach((entries) => {
    const [prop, key] = entries as [keyof BIWDController.State, string | string[]]
    const keys = Array.isArray(key) ? key : [key]
    keys.forEach((key) => {
      worker.useGetValueBinding(prop, {
        key,
        from: 'setting',
      })
    })
  })
  worker.useHasKeyBinding('isCoolWater', {
    key: BIWD_WATERTREATMENT_CHILLEDWATERSET,
    from: 'setting',
  })

  const runStatePatcher: Binder.StatePatcher<BIWDController.Store, ApplianceSetting> = (patchState, reference) => {
    const { item, value } = reference
    let bshValue = item.enumValues && item.enumValues[Number(value)] && item.enumValues[Number(value)].bshValue
    if (!bshValue) {
      bshValue = item.displayValue && item.displayValue.replace('BSH.Common.Status.OperationState.', '')
    }
    patchState.operateState = bshValue && bshValue.replace('BSH.Common.Status.OperationState.', '')
    patchState.runState = value as number
  }
  worker.useGetValueBinding('runState', {
    key: OperationState,
    from: 'setting',
    patcher: runStatePatcher,
  })
}
